from math import *
import math
import numpy as np
import os
# 返回n个反斜杠
def printBackSlash(n):
    Textbackslash = '\\'*n
    return Textbackslash

def mathSymbol(str):
    str = '$'+str+'$'
    return str

def createTableHead(path,                       #the directionary
                    captionType,                
                    caption, 
                    *tablehead
                    ):
    with open(path, 'w') as f:
        f.write("%stablehead{%shline " % (printBackSlash(1),printBackSlash(1)))
        for i in tablehead:
            if i != tablehead[-1]:
                f.write(i+' & ')
            else:
                f.write(i+' ')
        f.write("%s %shline}\n" % (printBackSlash(2),printBackSlash(1)))
        if captionType == 'buttom':
            f.write("%sbottomcaption{%s}\n" % (printBackSlash(1), caption))
        elif captionType == 'top':
            f.write("%stopcaption{%s}\n"% (printBackSlash(1), caption))
        else:
            f.write("%stablecaption{%s}\n" % (printBackSlash(1), caption))
        f.write("%stabletail{%shline}\n" % (printBackSlash(1),printBackSlash(1)))
        f.write("%sbegin{center}\n" % printBackSlash(1))
        f.write("%sbegin{supertabular}{%s}\n" % (printBackSlash(1),len(tablehead)*'c'))
        f.write("%shline\n" % printBackSlash(1))

def calculate(start,stop,steps,fun):
    result=[]

    for i in np.arange(start,stop+1,steps):
        result.append(fun(i))
    
    return result

def createTableTail(path):
    with open(path, 'a+') as f:
        f.write("%shline\n" % printBackSlash(1))
        f.write("%send{supertabular}\n" % printBackSlash(1))
        f.write("%send{center}\n" % printBackSlash(1))

def createTable(path,start,stop,steps,*fun):
    result_dict = {}
    for i in fun:
        result_dict[i]=calculate(start,stop,steps,i)
    keys = list(result_dict.keys())                 #字典是无序的，列表有序
    for i in range(len(result_dict[fun[1]])):      # 循环值的长度
        with open(path, 'a+') as f:
            for j in keys:
                val = result_dict[j]
                if j != keys[-1]:
                    f.write("{:.3f}".format(val[i])+' & ')
                else:
                    f.write("{:.3f}".format(val[i])+printBackSlash(2))
            f.write("\n")


def main():
    fileName = 'test.tex'
    path = '/home/xiaochen/tcipa/Project-Report-TR-PPP-Template-1.0/'+fileName
    
    fun1 = lambda x : x
    fun2 = lambda x : sin(radians(x))
    fun3 = lambda x : 5*x**2+3*x+3
    fun4 = lambda x : log10(x)
    fun5 = lambda x : 3*x+5
    createTableHead(path,'buttom','test',mathSymbol('x'),mathSymbol('sinx'),mathSymbol('5x^{2}+3x+3'),mathSymbol('log_{10}'),mathSymbol('3x+5'))
    createTable(path,2,10,0.1,fun1,fun2,fun3,fun4,fun5)
    createTableTail(path)

main()